"""
@Author：十
@Time：2024/11/19 16:11
@FileName：blueTransfer.py
@Description：蓝牙接收文件
"""


import asyncio
from bleak import BleakClient, BleakScanner

# 服务的UUID
SERVICE_UUID = "0000abf0-0000-1000-8000-00805f9b34fb"

# 特征的UUID
CHAR_UUID_SEND_DATA = "0000abf1-0000-1000-8000-00805f9b34fb"
CHAR_UUID_RECEIVE_DATA = "0000abf2-0000-1000-8000-00805f9b34fb"

filelist = "all files"

# 保存接收到的文件数据
OUTPUT_FILE = "received_file.txt"

# 用于存储接收到的数据
received_data = bytearray()


def notification_handler(sender, data):
    """处理接收到的数据"""
    global received_data
    received_data.extend(data)
    print(f"Received {len(data)} bytes of data")


async def main():
    global device

    # 扫描设备
    devices = await BleakScanner.discover()

    # 过滤出名为ble_server的设备
    ble_server_devices = [device for device in devices if device.name == "ble_server"]

    if not ble_server_devices:
        print("No device named 'ble_server' found.")
        return

    for device in ble_server_devices:
        print(f"Device Name: {device.name}")
        print(f"Device Address (MAC): {device.address}")

    # 扫描并连接到目标设备
    device = await BleakScanner.find_device_by_address(device.address)
    if not device:
        print(f"Could not find device with address {device.address}")
        return

    async with BleakClient(device) as client:
        print(f"Connected to {device.address}")

        try:
            # 订阅特征值变化，等待下位机发送数据
            await client.start_notify(CHAR_UUID_RECEIVE_DATA, notification_handler)
            print("Started waiting for data from the device")

            await client.write_gatt_char(CHAR_UUID_SEND_DATA, filelist.encode('ascii'))

            # 等待一段时间以便接收所有数据
            await asyncio.sleep(10)  # 根据实际情况调整等待时间

            # 停止订阅
            await client.stop_notify(CHAR_UUID_RECEIVE_DATA)
            print(f"files list:\n{received_data}")

            # 等待一段时间
            await asyncio.sleep(5)  # 根据实际情况调整等待时间

            # 清空接收到的数据
            received_data.clear()

            # 订阅特征值变化，等待下位机发送数据
            await client.start_notify(CHAR_UUID_RECEIVE_DATA, notification_handler)
            print("Started waiting for data from the device")

            # 要发送的文件名
            filename = input("Enter the filename to send: ")

            # 发送文件名
            await client.write_gatt_char(CHAR_UUID_SEND_DATA, filename.encode('ascii'))
            # TODO: 这里要检测文件的编码方式
            print(f"Sent filename: {filename}")

            # 等待一段时间以便接收所有数据
            await asyncio.sleep(10)  # 根据实际情况调整等待时间

            # 停止订阅
            await client.stop_notify(CHAR_UUID_RECEIVE_DATA)

            # 保存接收到的数据到文件
            with open(OUTPUT_FILE, "wb") as f:
                f.write(received_data)
            print(f"Saved received data to {OUTPUT_FILE}")

        except Exception as e:
            print(f"An error occurred: {e}")

# 运行主函数
asyncio.run(main())


